package init

import (
	"course-srv/basic/config"
	"course-srv/handler/models"
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"log"
	"time"
)

func MysqlInit() {
	var err error
	// 参考 https://github.com/go-sql-driver/mysql#dsn-data-source-name 获取详情
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		config.AppConf.Mysql.User,
		config.AppConf.Mysql.Password,
		config.AppConf.Mysql.Host,
		config.AppConf.Mysql.Port,
		config.AppConf.Mysql.Database,
	)

	config.DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		panic(err)
		return
	}
	log.Println("MySQL init success")

	err = config.DB.AutoMigrate(&models.User{}, &models.Function{}, &models.Course{}, &models.CourseType{}, &models.Collect{})
	if err != nil {
		panic(err)
		return
	}
	log.Println("数据库表迁移成功")

	sqlDB, err := config.DB.DB()

	// SetMaxIdleConns sets the maximum number of connections in the idle connection pool.
	sqlDB.SetMaxIdleConns(10)

	// SetMaxOpenConns sets the maximum number of open connections to the database.
	sqlDB.SetMaxOpenConns(100)

	// SetConnMaxLifetime sets the maximum amount of time a connection may be reused.
	sqlDB.SetConnMaxLifetime(time.Hour)
}
